package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop

import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.MyContract
import fm.dongman.animefm.contractlib.contract.UserListContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.adapter.UsedAdapter
import fm.dongman.animefm.view.listener.LoadMoreRecyclerOnScrollListener
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.UserModel
import fm.dongman.presenterlib.presenter.UserListPresenter
import kotlinx.android.synthetic.main.fragment_user_list.*
import kotlinx.android.synthetic.main.item_user_list.view.*
import org.jetbrains.anko.onClick

/**
 * 用户消息页面，一般用于显示用户粉丝或者关注再或者用户的搜索结果
 * Created by Administrator on 2017/10/26.
 */
class UserListFragment : BaseFragment(), UserListContract.IUserListView {
    private var mPresenter: UserListContract.IUserListPresenter? = null // 全局数据控制器
    private var mFlagType: String = TYPE_SEARCH // 用户列表类型
    private var mFlagId: String? = null // 用户id or key

    private lateinit var mScrollListener: LoadMoreRecyclerOnScrollListener // 滑动监听器

    private lateinit var mUserListAdapter: UserListAdapter // 用户列表适配器
    private val mUserList: ArrayList<IModel.IUserModel> = ArrayList() // 用户列表集合

    private lateinit var mFooterView: View // 列表底部 View

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = inflater!!.inflate(R.layout.fragment_user_list, container, false)
        UserListPresenter(this, Injection.provideUserListRepository())
        return view
    }

    override fun setNewParam(key: String) {
        mFlagId = key
        requestListData(1)
    }

    override fun requestListData(page: Int) {
        getUserList(page)
        mScrollListener.clearPage()
        mUserListAdapter.addFooterView(mFooterView)
        onStateChanged(MultiStateLayout.LOADING)
    }

    override fun initData() {
        if (arguments != null) {
            mFlagType = arguments.getString(FLAG_TYPE)
            if (mFlagId == null)
                mFlagId = arguments.getString(FLAG_ID)
        }
    }

    override fun bindData() {
        bindToolbar()
        bindUserList()
    }

    private fun bindToolbar() {
        mUserListToolbar.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        mUserListToolbar.setNavigationOnClickListener {
            ActivityHelper.backActivity(activity)
        }
        // 分情况加载类型标题
        when (mFlagType) {
            TYPE_FAN -> mUserListToolbar.title = getString(R.string.str_my_fans)
            TYPE_FOLLOW -> mUserListToolbar.title = getString(R.string.str_my_focus)
            TYPE_SEARCH -> mUserListToolbar.visibility = View.GONE
            else -> ToastHelper.getInstance(activity).showError("类型错误")
        }
    }

    @SuppressLint("InflateParams")
    private fun bindUserList() {
        mFooterView = LayoutInflater.from(activity).inflate(R.layout.layout_loading, null)
        mUserListAdapter = UserListAdapter(activity, mUserList)
        mUserListRecycler.adapter = mUserListAdapter
        mUserListRecycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        mScrollListener = object : LoadMoreRecyclerOnScrollListener(mUserListRecycler.layoutManager) {
            override fun onLoadMore(currentPage: Int) {
                getUserList(currentPage)
            }
        }
        mUserListRecycler.addOnScrollListener(mScrollListener)
        if (mFlagType == TYPE_SEARCH)
            requestListData(1)
    }

    /**
     * 获取用户列表
     */
    private fun getUserList(page: Int) {
        if (mFlagId == null && mFlagType == TYPE_SEARCH) {
            return
        }
        if (mFlagId == null) mFlagId = MyContract.USER_ID
        mPresenter?.setKey(page, mFlagType, mFlagId!!)
    }

    override fun setPresenter(presenter: UserListContract.IUserListPresenter) {
        mPresenter = presenter
    }

    override fun showNoNetwork() {
        onStateChanged(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        ToastHelper.getInstance(activity).showError(getString(R.string.str_refresh_failed))
        onStateChanged(MultiStateLayout.EMPTY)
    }

    override fun showUserList(users: List<IModel.IUserModel>) {
        onStateChanged(MultiStateLayout.SUCCESS)
        mUserList.clear()
        mUserList.addAll(users)
        mUserListAdapter.notifyDataSetChanged()
        if (users.size < 10) {
            // 加载完毕
            mUserListAdapter.removeFooterView()
        }
    }

    override fun showMoreUserList(users: List<IModel.IUserModel>) {
        mUserList.addAll(users)
        mUserListAdapter.notifyDataSetChanged()
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    /**
     * 切换状态
     */
    private fun onStateChanged(state: Int) {
        mUserListMultiState?.changeState(state)
    }

    companion object {
        /**
         * 若对应搜索，则传递关键字
         */
        private val FLAG_ID = "fm.dongman.animefm.flag.userList.id"
        /**
         * 对应 Presenter 接口的类型
         */
        private val FLAG_TYPE = "fm.dongman.animefm.flag.userList.type"

        val TYPE_SEARCH = UserListContract.IUserListPresenter.TYPE_SEARCH // 搜索
        val TYPE_FOLLOW = UserListContract.IUserListPresenter.TYPE_FOLLOW // 关注
        val TYPE_FAN = UserListContract.IUserListPresenter.TYPE_FAN // 粉丝

        /**
         * 获取实例
         *
         * @param flagType 类型
         * @param flagId   id
         * @return UserListFragment
         */
        fun getInstance(flagType: String, flagId: String?): UserListFragment {
            val fragment = UserListFragment()
            val bundle = Bundle()
            bundle.putString(FLAG_TYPE, flagType)
            bundle.putString(FLAG_ID, flagId)
            fragment.arguments = bundle
            return fragment
        }
    }

    /**
     * 用户列表适配器
     */
    private class UserListAdapter constructor(private val mContext: Context, private val mData: List<IModel.IUserModel>)
        : UsedAdapter<UserListAdapter.UserListViewHolder>() {
        @SuppressLint("InflateParams")
        override fun onCreateVH(): UserListViewHolder =
                UserListViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_user_list, null))

        override fun onBindVH(holder: UserListViewHolder, position: Int) {
            val user = mData[position] as UserModel
            Glide.with(mContext)
                    .load(user.avatarUrl)
                    .bitmapTransform(CenterCrop(mContext), GlideRoundTransform(mContext, 24))
                    .placeholder(R.mipmap.avatar)
                    .into(holder.mAvatar)
            holder.mUserName.text = user.userName
            if (!TextUtils.isEmpty(user.description)) {
                holder.mDesc.text = user.description
            }
            holder.itemView.onClick {
                val intent = Intent(mContext, SingleActivity::class.java)
                intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_USER_INFO)
                intent.putExtra(SingleActivity.BUNDLE_EXTRA_KEY_ID, user.userId)
                mContext.startActivity(intent)
            }
        }

        override fun getDataTotal(): Int = mData.size

        private class UserListViewHolder(itemView: View) : UsedViewHolder(itemView) {
            val mAvatar = itemView.mIvUserListAvatar!!
            val mUserName = itemView.mIvUserListUserName!!
            val mDesc = itemView.mIvUserListDescription!!
        }
    }
}
